package cn.imvc.app.controllers;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.puff.cache.redis.Redis;

import cn.imvc.app.domains.AppResult;
import cn.imvc.app.entities.Account;
import cn.imvc.app.entities.Bankcard;
import cn.imvc.app.entities.FundFlow;
import cn.imvc.app.entities.Member;
import cn.imvc.app.entities.Recharge;
import cn.imvc.app.entities.Voucher;
import cn.imvc.app.models.AccountModel;
import cn.imvc.app.models.BankModel;
import cn.imvc.app.models.BankcardModel;
import cn.imvc.app.models.CommissionModel;
import cn.imvc.app.models.DealerLevelModel;
import cn.imvc.app.models.FundFlowModel;
import cn.imvc.app.models.MemberModel;
import cn.imvc.app.models.RechargeModel;
import cn.imvc.app.models.VoucherModel;
import cn.imvc.app.models.WithdrawalsModel;
import cn.imvc.util.PageableUtils;

@Controller
@RequestMapping("money")
public class MoneyControllerImpl implements MoneyController {

	@Autowired
	MemberModel memberModel;

	@Autowired
	AccountModel accountModel;

	@Autowired
	RechargeModel rechargeModel;

	@Autowired
	WithdrawalsModel withdrawalsModel;

	@Autowired
	BankcardModel bankcardModel;

	@Autowired
	BankModel bankModel;

	@Autowired
	FundFlowModel fundFlowModel;

	@Autowired
	VoucherModel voucherModel;

	@Autowired
	DealerLevelModel dealerLevelModel;

	@Autowired
	CommissionModel commissionModel;

	private static final Logger log = Logger.getLogger(MoneyControllerImpl.class);

	@RequestMapping("money.html")
	public String money(Model model, String token) {
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			return "redirect:/member/login.html";
		}
		// 通过token从缓存里取member
		Member member = memberModel.getLoginMember(token);
		member = memberModel.get(member.getId());
		model.addAttribute("isProxy", member.getDealer().getDealerLevel().getType() == (byte) 2);
		model.addAttribute("purse", member.getAccount().getPurse());
		model.addAttribute("commissions", member.getAccount().getCommissions());
		return "money/money";
	}

	@RequestMapping("recharge.html")
	public String recharge(Model model, String token) {
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			return "redirect:/member/login.html";
		}
		// 通过token从缓存里取member
		Member member = memberModel.getLoginMember(token);
		member = memberModel.get(member.getId());
		model.addAttribute("money", member.getAccount().getPurse());
		return "money/recharge";
	}

	@RequestMapping("recharge.htm")
	public String pcrecharge(Model model, String token) {
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			return "redirect:/member/login.htm";
		}
		// 通过token从缓存里取member
		Member member = memberModel.getLoginMember(token);
		member = memberModel.get(member.getId());
		model.addAttribute("money", member.getAccount().getPurse());
		return "money/pcrecharge";
	}

	@RequestMapping("saveRechargeOrder.json")
	@ResponseBody
	public Map<String, Object> saveRechargeOrder(Model model, String token, Integer money) {

		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			resultMap.put("code", "-1");
			resultMap.put("msg", "未登录");
			return resultMap;
		}
		if (money == null || money <= 0) {
			resultMap.put("code", "0");
			resultMap.put("msg", "错误的金额");
			return resultMap;
		}
		// 通过token从缓存里取member
		Member member = memberModel.getLoginMember(token);
		member = memberModel.get(member.getId());
		Recharge recharge = rechargeModel.saveRechargeOrder(money, member);
		resultMap.put("code", 1);
		resultMap.put("msg", "保存订单成功");
		resultMap.put("orderCode", recharge.getCode());
		resultMap.put("orderId", recharge.getId());
		return resultMap;
	}

	@RequestMapping("withdrawals.html")
	public String withdrawals(Model model, String token, Integer bankcardId) {
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			return "redirect:/member/login.html";
		}

		// 通过token从缓存里取member
		Member member = memberModel.getLoginMember(token);
		member = memberModel.get(member.getId());

		Bankcard bankcard = null;
		if (bankcardId == null) {
			bankcard = bankcardModel.findDefaultCard(member.getId(), (byte) 1);
		} else {
			bankcard = bankcardModel.get(bankcardId);
		}
		model.addAttribute("key", member.getAccount().getKey1());
		model.addAttribute("purse", member.getAccount().getPurse());
		model.addAttribute("bankcardId", bankcard == null ? 0 : bankcard.getId());
		model.addAttribute("bankcardName",
				bankcard == null ? "空"
						: (bankcard.getBank().getName()
								+ bankcard.getBankCode().substring(bankcard.getBankCode().length() - 4)));
		return "money/withdrawals";
	}

	@RequestMapping("withdrawals.htm")
	public String pcwithdrawals(Model model, String token) {
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			return "redirect:/member/login.htm";
		}

		// 通过token从缓存里取member
		Member member = memberModel.getLoginMember(token);
		member = memberModel.get(member.getId());

		model.addAttribute("key", member.getAccount().getKey1());
		model.addAttribute("purse", member.getAccount().getPurse());
		model.addAttribute("bankcardList", member.getBankcard());
		return "money/pcwithdrawals";
	}

	@RequestMapping("saveWithdrawalsOrder.json")
	@ResponseBody
	public Map<String, Object> saveWithdrawalsOrder(Model model, String token, Integer money, Integer bankcardId,
			String payPass) {

		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			resultMap.put("code", "-1");
			resultMap.put("msg", "未登录");
			return resultMap;
		}

		// 通过token从缓存里取member
		Member member = memberModel.getLoginMember(token);
		member = memberModel.get(member.getId());
		Account account = member.getAccount();

		if (money == null || money <= 0) {
			resultMap.put("code", "0");
			resultMap.put("msg", "错误的金额");
			return resultMap;
		}

		if (money > account.getPurse()) {
			resultMap.put("code", "0");
			resultMap.put("msg", "没有足够的钱来提现");
			return resultMap;
		}
		if (payPass == null || (!accountModel.checkPayPw(account, payPass))) {
			resultMap.put("code", "0");
			resultMap.put("msg", "请输入正确的支付密码");
			return resultMap;
		}
		if (bankcardId == null || bankcardId == 0) {
			resultMap.put("code", "0");
			resultMap.put("msg", "请选择银行卡");
			return resultMap;
		}

		try {
			withdrawalsModel.saveWithdrawalsOrder(money, member, bankcardId);
		} catch (Exception e) {
			resultMap.put("code", 0);
			resultMap.put("msg", "账户异常");
			return resultMap;
		}
		resultMap.put("code", 1);
		resultMap.put("msg", "提现订单已保存，请等待审核");
		return resultMap;
	}

	@RequestMapping("fundflow.html")
	public String fundflow(Model model, String token, String type) {
		Member member = memberModel.getLoginMember(token);
		if (member != null) {
			model.addAttribute("type", type);
			return "money/fundflow";
		} else {
			return "redirect:/member/login.html";
		}
	}

	@RequestMapping("fundflowlist.html")
	public String fundflowlist(Model model, String token, Byte type, Integer page) {
		Member member = memberModel.getLoginMember(token);
		if (member != null) {
			Page<FundFlow> result = fundFlowModel.findMoneyPage(member, page, type);
			model.addAttribute("fundFlowList", result.getContent());
			model.addAttribute("over", page == result.getTotalPages() ? true : false);
			return "money/fundflowlist";
		} else {
			return "redirect:/member/login.html";
		}
	}

	@RequestMapping("money.htm")
	public String pcmoney(Model model, String token) {
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			return "redirect:/member/login.htm";
		}
		// 通过token从缓存里取member
		Member member = memberModel.getLoginMember(token);
		member = memberModel.get(member.getId());
		model.addAttribute("isProxy", member.getDealer().getDealerLevel().getType() == (byte) 2);
		model.addAttribute("purse", member.getAccount().getPurse());
		model.addAttribute("commissions", member.getAccount().getCommissions());
		return "money/pcmoney";
	}

	@RequestMapping("fundflowlist.htm")
	public String pcfundflowlist(Model model, String token, Byte type, Integer page) {
		Member member = memberModel.getLoginMember(token);
		if (member != null) {
			page--;
			PageRequest pageRequest = new PageRequest(page, 9, null);
			Page<FundFlow> result = fundFlowModel.findMoneyPage(member, pageRequest, type);
			model.addAttribute("fundFlowList", result.getContent());
			model.addAttribute("count", result.getTotalPages());
			return "money/pcfundflowlist";
		} else {
			return "redirect:/member/login.htm";
		}
	}

	@RequestMapping("/voucher.html")
	public String voucher(String token) {
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			return "redirect:/member/login.html";
		}

		return "money/voucher";
	}

	@RequestMapping("/voucher.htm")
	public String pcvoucher(Model model, String token) {
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			return "redirect:/member/login.htm";
		}
		return "money/pcvoucher";
	}

	@RequestMapping("/getVoucher.html")
	public String getVoucher(Model model, String token, Integer page) {
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			return "redirect:/member/login.html";
		}
		Member member = memberModel.getLoginMember(token);
		PageRequest pageRequest = PageableUtils.bulidPageRequest(page, 10, "startDate_DESC", true);
		Page<Voucher> vouchers = voucherModel.findByMemberId(member.getId(), pageRequest);
		model.addAttribute("vouchers", vouchers.getContent());
		if (vouchers.getTotalPages() == (page + 1)) {
			model.addAttribute("over", true);
		} else {
			model.addAttribute("over", false);
		}
		model.addAttribute("now", new Date());
		return "money/voucher-list";
	}

	@RequestMapping("/getVoucher.htm")
	public String pcgetVoucher(Model model, String token, Integer page) {
		page--;
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			return "redirect:/member/login.htm";
		}
		Member member = memberModel.getLoginMember(token);
		PageRequest pageRequest = PageableUtils.bulidPageRequest(page, 6, "startDate_DESC", true);
		Page<Voucher> vouchers = voucherModel.findByMemberId(member.getId(), pageRequest);
		model.addAttribute("vouchers", vouchers.getContent());
		model.addAttribute("count", vouchers.getTotalPages());
		model.addAttribute("now", new Date());
		return "money/pcvoucher-list";
	}

	@RequestMapping("exchange.html")
	public String exchange(Model model, String token) {
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			return "redirect:/member/login.html";
		}

		// 通过token从缓存里取member
		Member member = memberModel.getLoginMember(token);
		member = memberModel.get(member.getId());
		try {
			model.addAttribute("list",
					withdrawalsModel.findPointsToMoney(member.getDealer().getDealerLevel().getLevel()));
		} catch (Exception e) {
			log.error(member.getId() + "    " + e.toString());
		}
		model.addAttribute("key", member.getAccount().getKey1());
		model.addAttribute("points", member.getAccount().getPoints());
		return "money/exchange";
	}
	
	@RequestMapping("exchange.htm")
	public String pcexchange(Model model, String token) {
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			return "redirect:/member/login.html";
		}

		// 通过token从缓存里取member
		Member member = memberModel.getLoginMember(token);
		member = memberModel.get(member.getId());
		try {
			model.addAttribute("list",
					withdrawalsModel.findPointsToMoney(member.getDealer().getDealerLevel().getLevel()));
		} catch (Exception e) {
			log.error(member.getId() + "    " + e.toString());
		}
		model.addAttribute("key", member.getAccount().getKey1());
		model.addAttribute("points", member.getAccount().getPoints());
		return "money/pcexchange";
	}

	@RequestMapping("savePToMOrder.json")
	@ResponseBody
	public Map<String, Object> savePToMOrder(Model model, String token, Integer points, Integer listId,
			String payPass) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			resultMap.put("code", "-1");
			resultMap.put("msg", "未登录");
			return resultMap;
		}

		// 通过token从缓存里取member
		Member member = memberModel.getLoginMember(token);
		member = memberModel.get(member.getId());
		Account account = member.getAccount();

		if (points == null || points <= 0) {
			resultMap.put("code", "0");
			resultMap.put("msg", "错误的积分");
			return resultMap;
		}

		if (points > account.getPoints()) {
			resultMap.put("code", "0");
			resultMap.put("msg", "没有足够的积分来兑换");
			return resultMap;
		}
		if (payPass == null || (!accountModel.checkPayPw(account, payPass))) {
			resultMap.put("code", "0");
			resultMap.put("msg", "请输入正确的支付密码");
			return resultMap;
		}

		if (listId == null || listId == 0) {
			resultMap.put("code", "0");
			resultMap.put("msg", "请选择兑换方式");
			return resultMap;
		}
		AppResult appResult = null;
		try {
			if (Redis.getInstance().setnx("PToM" + token, "aa") == 1) {
				Redis.getInstance().expire("PToM" + token, 20);
				appResult = withdrawalsModel.savePToMOrder(points, member, listId);
				Redis.getInstance().remove("PToM" + token);
			} else {
				resultMap.put("code", "0");
				resultMap.put("msg", "正在操作");
			}
		} catch (Exception e) {
			Redis.getInstance().remove("PToM" + token);
			resultMap.put("code", "0");
			resultMap.put("msg", "账户异常");
			return resultMap;
		}
		resultMap.put("code", appResult.getCode());
		resultMap.put("msg", appResult.getMsg());

		return resultMap;

	}

}
